/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.epidemy.util

object SerializationUtils {
  def serialize(o: Any): Array[Byte] = {
    import java.io._
    val out = new ByteArrayOutputStream
    val dout = new ObjectOutputStream(out)
    dout.writeObject(o)
    dout.close
    out.toByteArray
  }
  def deserializer(b: Array[Byte], classLoader: ClassLoader = null): () => Any = {
    import java.io._
    val in = new ByteArrayInputStream(b)
    val din = if (classLoader == null)
      new ObjectInputStream(in)
    else
      new ObjectInputStream(in) {
        //enableResolveObject(true)
        override def resolveClass(osc: ObjectStreamClass): Class[_] =
          try {
            classLoader.loadClass(osc.getName())
          } catch {
            case ex: ClassNotFoundException =>
              ex.printStackTrace
              super.resolveClass(osc)
          }
        override def resolveProxyClass(interfaces: Array[String]): Class[_] =
          try {
            java.lang.reflect.Proxy.getProxyClass(classLoader, interfaces.map(classLoader.loadClass): _*)
          } catch {
            case ex: ClassNotFoundException =>
              ex.printStackTrace
              super.resolveProxyClass(interfaces)
          }
      }
    () => din.readObject
  }
  def deserialize(b: Array[Byte], classLoader: ClassLoader = null): Any = deserializer(b, classLoader)()
}
